﻿using Core.Core;
using Core.Modal;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace www.api
{
    /// <summary>
    /// TagHandler 的摘要说明
    /// </summary>
    public class TagHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            context.Response.ContentType = "text/plain";
            try
            {
                string func = context.Request["function_type"].ToString();
                switch (func)
                {
                    case "addTag":
                        addTag(context);
                        break;
                    case "delTag":
                        delTag(context);
                        break;
                }
            }
            catch (Exception ex)
            {
                context.Response.Write(new ResponseData("400", ex.Message.ToString(), "").ToString());
            }
        }

        private void delTag(HttpContext context)
        {
            int project_id = Convert.ToInt32(context.Request["project"].ToString());
            int id = Convert.ToInt32(context.Request["id"].ToString());

            TagUtil.Delete(project_id, id);

            context.Response.Write(new ResponseData("200", "标记删除成功", id).ToString());
        }

        /// <summary>
        /// 
        /// </summary>
        /// <param name="context"></param>
        private void addTag(HttpContext context)
        {
            int project_id = Convert.ToInt32(context.Request["project"].ToString());
            int id = Convert.ToInt32(context.Request["id"].ToString());
            string name = context.Request["name"].ToString();
            string comment = context.Request["comment"].ToString();
            string tag_type = context.Request["tag_type"].ToString();
            string content = context.Request["content"].ToString();
            string files = context.Request["docs"].ToString();//

            JArray f = (JArray)JsonConvert.DeserializeObject(files);

            if (id != 0)
            {
                TagUtil.Update(project_id, Convert.ToInt32(id), name, comment, tag_type, content,f);
            }
            else
            {
                id = TagUtil.Add(project_id, name, comment, tag_type, content, f);
            }
            if (id != 0)
            {
                context.Response.Write(new ResponseData("200", "标记保存成功", id).ToString());
            }
            else
            {
                context.Response.Write(new ResponseData("400", "标记保存失败", "").ToString());
            }
        }


        public bool IsReusable
        {
            get
            {
                return false;
            }
        }
    }
}